package com.lebang.service;

import com.lebang.configuration.datasource.DataSource;
import com.lebang.domain.TaskTagRelation;
import com.lebang.entity.task.TaskScreenshot;
import com.lebang.example.TaskTagRelationExample;
import com.lebang.mapper.TaskScreenshotMapper;
import com.lebang.mapper.TaskTagRelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TaskScreenshotService {

    @Autowired
    private TaskScreenshotMapper taskScreenshotMapper;

    @Autowired
    private TaskTagRelationMapper taskTagRelationMapper;

    /**
     * 根据任务id查找截图任务总表
     * @param taskId
     * @return
     */
    public TaskScreenshot selectByTaskId(String taskId) {
        return taskScreenshotMapper.selectByTaskId(taskId);
    }

    /**
     * 新增数据到截图任务总表
     * @param taskScreenshot
     */
    @DataSource("commonDB")
    public void insert(TaskScreenshot taskScreenshot) {
        taskScreenshotMapper.insertSelective(taskScreenshot);
    }

    /**
     * 修改截图任务总表
     * @param taskScreen
     */
    @DataSource("commonDB")
    public void update(TaskScreenshot taskScreen) {
        taskScreenshotMapper.updateByPrimaryKeySelective(taskScreen);
    }

    @DataSource("commonDB")
    public List<String> selectRelation(String taskid) {
        List<String> list = new ArrayList<>();
        TaskTagRelationExample example = new TaskTagRelationExample();
        example.createCriteria().andTaskIdEqualTo(taskid);
        List<TaskTagRelation> taskTagRelations = taskTagRelationMapper.selectByExample(example);
        taskTagRelations.forEach(s -> {
            list.add(s.getTagId().toString());
        });
        return list;
    }

    /**
     * 新增任务标签关联表
     * @param taskId
     * @param taskTagId
     */
    @DataSource("commonDB")
    public void insertTagRelation(String taskId, String taskTagId) {
        String[] ids = taskTagId.split(",");
        for (int i = 0; i < ids.length; i++) {
            TaskTagRelation taskTagRelation = new TaskTagRelation();
            taskTagRelation.setTagId(Integer.parseInt(ids[i]));
            taskTagRelation.setTaskId(taskId);
            taskTagRelationMapper.insertSelective(taskTagRelation);
        }
    }

    /**
     * 删除任务标签关系表对应任务id的标签
     * @param taskId
     */
    @DataSource("commonDB")
    public void deleteTagRelation(String taskId) {
        TaskTagRelationExample example = new TaskTagRelationExample();
        example.createCriteria().andTaskIdEqualTo(taskId);
        taskTagRelationMapper.deleteByExample(example);
    }

    public List<TaskScreenshot> selectByTitle(String title,Integer startNum,Integer pageSize) {
        return taskScreenshotMapper.selectByTitle(title,startNum,pageSize);
    }

    public Integer countByTitle(String title) {
        return taskScreenshotMapper.countByTitle(title);
    }
}
